package com.api.aiyh_pcn.copy_attachment.dao;

import aiyh.utils.Util;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.zwl.common.ToolUtil;
import org.apache.axiom.util.base64.Base64Utils;
import org.apache.commons.io.IOUtils;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocManager;
import weaver.file.ImageFileManager;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.FileProcessor;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author EBU7-dev1-ayh
 * @create 2021/8/26 0026 11:14
 * copy mybatisTest.dao
 */


public class DocTemplateDao {
	ToolUtil toolUtil = new ToolUtil();
	private int userId;

	public int[] copyFile(User user,String tableName, String fieldName, String configId,String workflowId, String fileFieldId){
		this.userId = user.getUID();
		String[] templateData = ConfigTableData.getTemplateData(tableName, fieldName, configId);
		String joinId = String.join(",", templateData);
//		查询物理文件id
		String query = "select imagefileid,imagefilename from docimagefile where docid in (" + joinId + ")";
		RecordSet rs = new RecordSet();
		rs.executeQuery(query);
		FileProcessor fileProcessor = new FileProcessor();
		String docCategorys = Util.getDocCategorys(workflowId, fileFieldId);
		List<Integer> docIds = new ArrayList<>();
		while (rs.next()){
//			获取物理文件id和物理文件名
			String id = rs.getString("imagefileid");
			String name = rs.getString("imagefilename");
			InputStream inputStreamById = ImageFileManager.getInputStreamById(Integer.parseInt(id));
			byte[] bytes = new byte[0];
			try {
				bytes = IOUtils.toByteArray(inputStreamById);
			} catch (IOException e) {
				e.printStackTrace();
				toolUtil.writeErrorLog("复制文件时，文件转为base64出错，文件转换出错！" + e);
			}
			String base64 = Base64Utils.encode(bytes);
			int docid = fileProcessor.Process("base64:" + base64, docCategorys, user, name);
			docIds.add(docid);
		}
		Integer[] strings = docIds.toArray(new Integer[0]);
		return Arrays.stream(strings).mapToInt(Integer::valueOf).toArray();
//		return ;
	}

	public int[] copyFile(int userId, String tableName, String fieldName, String configId) {
		this.userId = userId;
		String[] templateData = ConfigTableData.getTemplateData(tableName, fieldName, configId);
		this.toolUtil.writeDebuggerLog("模板数据：" + Arrays.toString(templateData));
		int[] array = Arrays.stream(templateData).mapToInt(Integer::parseInt).toArray();
		return this.copyFile(array);
	}

	private int[] copyFile(int... ids) {
		RecordSet rs = new RecordSet();
//		传入需要拷贝的附件的id
		DocManager docManager = new DocManager();
		int[] docIds = new int[ids.length];
		try {
			for (int i = 0; i < ids.length; i++) {
				//		设置需要拷贝的附件的id
				docManager.setId(ids[i]);
				//			进行附件的拷贝
				docManager.copyDocNew();
				//			获取到新拷贝的附件的id
				docIds[i] = docManager.getId();
//				对新文档进行权限重置
				rs.executeProc("DocSecCategoryShare_SBySecCate", String.valueOf(docManager.getId()));
			}
			return docIds;
		} catch (Exception e) {
			this.toolUtil.writeErrorLog("复制错误" + e);
			return null;
		}
	}

	public boolean updateFileInfo(String workflowId, String fileFieldId, int... ids) {
		RecordSet rs = new RecordSet();
//		通过流程查询到该流程对应的目录
		String query = "select catelogType, (case when catelogType = 9 then " +
				"(select docCategory from workflow_base where id = ?) else docCategory end )" +
				" as docCategory from workflow_fileupload " +
				"where workflowid = ? and fieldid = ?";

		rs.executeQuery(query, workflowId, workflowId, fileFieldId);
		String catelogType = "";
		String docCategory = "";
		if (rs.next()) {
			catelogType = rs.getString("catelogType");
			docCategory = rs.getString("docCategory");
		}
		this.toolUtil.writeDebuggerLog(catelogType + "," + docCategory);
		if (!"1".equals(catelogType)) {
			List<Object> list = new ArrayList<>();
			for (int id : ids) {
				list.add(id);
			}
			ResourceComInfo resourceComInfo = null;
			try {
				resourceComInfo = new ResourceComInfo();
			} catch (Exception e) {
				e.printStackTrace();
			}
			String departmentID = resourceComInfo.getDepartmentID(String.valueOf(this.userId));
//			附件目录不为自己选择，更新文件的目录信息和其他信息
			Map<String, Object> updateMap = Util.createUtilHashMap().uPut("ownerid", this.userId)
					.uPut("maincategory", 0)
					.uPut("subcategory", 0)
					.uPut("docstatus", 0)
					.uPut("shareroleid", this.userId)
					.uPut("doccreaterid", this.userId)
					.uPut("doclastmoduserid", this.userId)
					.uPut("docdepartmentid", departmentID)
					.uPut("doclastmoddate", Util.getTime("yyyy-MM-dd"))
					.uPut("doccreatedate", Util.getTime("yyyy-MM-dd"))
					.uPut("doclastmodtime", Util.getTime("HH:mm:ss"))
					.uPut("doccreatetime", Util.getTime("HH:mm:ss"))
					.uPut("seccategory", docCategory.split(",")[docCategory.split(",").length - 1]);
			Where whereIn = Util.createPrepWhereImpl().whereAnd("id").whereInList(list);
			PrepSqlResultImpl updateResult = Util.createSqlBuilder().updateSql("docdetail", updateMap, whereIn);
			this.toolUtil.writeDebuggerLog(updateResult.getSqlStr() + " : " + updateResult.getArgs());
			return rs.executeUpdate(updateResult.getSqlStr(), updateResult.getArgs());
		}
		return false;
	}

	public boolean deleteFile(int... ids) throws Exception {
		DocManager docManager = new DocManager();
		for (int id : ids) {
			try {
				docManager.setId(id);
				docManager.DeleteDocInfo();
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}
		}
		return true;
	}
}
